package com.moon.game.database;

import java.net.UnknownHostException;

import org.apache.log4j.Logger;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.MongoOptions;
import com.mongodb.ServerAddress;
import com.mongodb.util.JSON;
import com.moon.game.util.GDateUtils;

public class MongoUtil {
	private static final Logger log = Logger.getLogger(MongoUtil.class);
	/**
	 * 创建Mongo实例
	 * 
	 * @param host
	 * @param port
	 * @param dbName
	 * @return
	 */
	public static Mongo createMongo(String host, int port) {
		try {
			MongoOptions options = new MongoOptions();
			options.autoConnectRetry = true;
			// options.threadsAllowedToBlockForConnectionMultiplier = 3;
			// options.connectionsPerHost = 2;
			Mongo mongo = new Mongo(new ServerAddress(host, port), options);
			log.info("new mongo:hashCode:"+mongo.hashCode() + "[|] debugString" +mongo.debugString());
			return mongo;
		} catch (UnknownHostException ex) {
			log.error("UnknownHostException:" + ex.getMessage(),ex);
		} catch (MongoException ex) {
			log.error("Mongo Exception:{}|{}"+ex.getMessage(),ex);
		}
		return null;
	}
	
	
	/**
	 * 从DB查询数据
	 * 
	 * @param id
	 * @param isSlave
	 * @return
	 * @throws Exception
	 */
	public static String getDataFromDb(Mongo mongo, String id, String dbName,String collectionName) throws Exception {
		try {
			DB db = mongo.getDB(dbName);
			DBCollection dbcoll = db.getCollection(collectionName);
			BasicDBObject query = new BasicDBObject();
			query.put("_id", id);
			DBObject dbo = dbcoll.findOne(query);
			if (dbo != null) {
				DBObject data = (DBObject) dbo.get("data");
				String json = JSON.serialize(data);
				return json;
			}
		} catch (Exception e) {
			throw e;
		}
		return null;
	}
	
	/**
	 * 更新数据到DB
	 * 
	 * @param id
	 * @param b
	 */
	public static void saveData2Db(Mongo mongo,String id,String dbName,String collectionName, DBObject b) {
		DB db = mongo.getDB(dbName);
		DBCollection dbcoll = db.getCollection(collectionName);
		DBObject dblist = new BasicDBObject();
		dblist.put("_id", id);
		dblist.put("data", b);
		dblist.put("ac", GDateUtils.now());
//		dblist.put("hash", id.hashCode());
		dbcoll.save(dblist);
	}
}
